var BACK_SHOW_HEIGHT = 120;//滚动多少返回顶部显示
var GOLBAL_TIMER = null;
var GOLBAL_TIMROUT = null;

//图片加载
(function () {
    var imgLength = $('img').length;
    var count = 0;
    $('img').each(function (index, item) {
        imgLoad(item, function () {
            count++;
            var progress = Math.round(count / imgLength) * 100;
            if (progress >= 100) {
                $('.global_progress').fadeOut();
                progress = 100;
            }
            $('.global_progress').find('span').html('' + progress + '%');
            $('.progress_strip').animate({width: progress + '%'}, 10)
        })
    });

    function imgLoad(img, callback) {
        var timer = setInterval(function () {
            if (img.complete) {
                callback(img);
                clearInterval(timer)
            }
        }, 50)
    };
})();

$(function () {
    //1200 765 476
    //920 620 360
    var PART_ONE_DEVIATION = 131;
    var PART_THREE_MODEL = 60;
    var isBtn = false;
    var curTop = 0;
    var headerHeight = 0;

    //响应的宽高度
    var width1 = 1200;
    var width2 = 765;
    var width3 = 476;

    var height1 = 905;
    var height2 = 620;
    var height3 = 360;
    var BG_WIDTH = 1909;

    //联系我们用到的关键数据
    var isFooterBottom = false;
    var isFooterShow = false;
    var footerTop = getElementTop($('.footer').get(0));

    //窗口缩放头部响应
    window.addEventListener('scroll', initHeader(), false);

    //初始化头部
    function initHeader() {
        var El = $('.header').find('.container'),
            elHeight = El.height();
        if (!El.isMin && document.body.scrollTop >= elHeight) {
            El.addClass('active');
            $('.nav_bar').addClass('active');
            headerHeight = 60;
            El.isMin = true;
            El.isBig = false;
        }

        if (!El.isBig && document.body.scrollTop <= elHeight) {
            El.removeClass('active');
            $('.nav_bar').removeClass('active')
            headerHeight = 90;
            El.isBig = true;
            El.isMin = false;
        }
        return initHeader;
    };

    //onload ElemInit
    ElemtInit();
    //窗口改变元素响应
    window.addEventListener('resize', function () {
        __delay(200, function () {
            var part1_height = window.innerHeight - PART_ONE_DEVIATION;
            var part3_model_height = window.innerHeight - PART_THREE_MODEL;

            if (window.innerWidth < width1 && window.innerWidth >= width2) {
                part3_model_height = Math.max(part3_model_height, 329);
                part1_height = Math.max(part1_height, 476)
                $('.part_one').css({height: part1_height + 'px'});
            } else if (window.innerWidth < width2 && window.innerWidth >= width3) {
                part3_model_height = Math.max(part3_model_height, 319);
                $('.part_one').css({height: part1_height + 'px'});
            } else if (window.innerWidth < width3) {
                part3_model_height = Math.max(part3_model_height, 309);
                $('.part_one').css({height: 'auto'});
            } else {
                part3_model_height = Math.max(part3_model_height, 512);
                part1_height = Math.max(part1_height, 675);
                $('.part_one').css({height: part1_height + 'px'});
            }

            ElemtInit();
            $('.part_three').find('.model').css({height: part3_model_height + 'px'});
        });
    }, false);

    //初始化一些首页元素
    function ElemtInit() {
        if (window.innerWidth < width1) {
            $('.nav_bar').addClass('js_hook');
            $('.model_bg').find('img').css({
                maxWidth: 'none',
                maxHeight: 'none',
                width: BG_WIDTH + 'px',
                marginLeft: ~~((BG_WIDTH - window.innerWidth) / 2) * -1,
                height: '100%',
                marginTop: 0
            });
        } else {
            $('.model_bg').find('img').css({
                maxWidth: 'none',
                maxHeight: 'none',
                width: '100%',
                marginLeft: 0,
                height: '960px',
                marginTop: '-45px'
            });
            $('.nav_bar').removeClass('js_hook');
        }
        isBtn = false;
        $('.scroll_bar').removeClass('active').css({top: 0});
    }

    //点击导航下滑菜单
    $('.hidden_menu').click(function () {
        $(this).toggleClass('active');
        $('.nav_bar').slideToggle()
    });

    //点击更多客户下滑
    $('.part_two').find('.more').click(function () {
        if (!this.isDown) {
            $(this).find('a').html('关闭');
            this.isDown = true;
        } else {
            $(this).find('a').html('更多客户');
            this.isDown = false;
        }
        $('.more_wrapper').slideToggle();
        return false;
    });


    //网页滚动进度显示
    window.addEventListener('scroll', function () {
        var bodyHeight = document.body.scrollHeight;
        var wH = window.innerHeight;
        var totalScrollTop = bodyHeight - wH;
        var progress = ~~((document.body.scrollTop / totalScrollTop) * 100);
        if (!isBtn) {
            curTop = getElementTop($('.scroll_bar').get(0));
            isBtn = true;
        }
        if (document.body.scrollTop >= curTop - headerHeight) {
            $('.scroll_bar').addClass('active').css({top: headerHeight + 'px'});
        } else {
            $('.scroll_bar').removeClass('active').css({top: 0});
        }
        $('.scroll_bar').find('.scroll').css({width: progress + '%'});
    }, false);


    //back 的显示
    window.addEventListener('scroll', function () {
        var El = $('.back');
        if (document.body.scrollTop > BACK_SHOW_HEIGHT) {
            El.addClass('showing').removeClass('hiding');
            El.isHiding = false;
            El.isShowing = true;
        }

        if (!El.isHiding && document.body.scrollTop < BACK_SHOW_HEIGHT) {
            El.addClass('hiding').removeClass('active');
            El.isHiding = true;
            El.isShowing = false;
        }

        checkIsBottom(isFooterShow, isFooterBottom);
    }, false);

    //back的点击
    $('.back').click(function () {
        var scrollTop = document.body.scrollTop;
        var timer = setInterval(upTop, 1000 / 60);

        function upTop() {
            scrollTop -= 80;
            if (scrollTop <= 0) {
                clearInterval(timer);
                scrollTop = 0;
            }
            document.body.scrollTop = scrollTop;
        }
    });

    //点击客户滑动
    $('.customer_l').click(function () {
        var customerTop = getElementTop($('.part_two').get(0));
        var scrollTop = document.body.scrollTop;
        var tiemr = null;
        if (customerTop - scrollTop > 0) {
            timer = setInterval(function () {
                scrollTop += 30;
                if (scrollTop >= customerTop) {
                    clearInterval(timer);
                }
                document.body.scrollTop = scrollTop;
            }, 1000 / 60);
        } else {
            timer = setInterval(function () {
                scrollTop -= 30;
                if (scrollTop <= customerTop) {
                    clearInterval(timer);
                }
                document.body.scrollTop = scrollTop;
            }, 1000 / 60);
        }
    });

    //点击联系我们底部滑出
    $('.concat_l').click(function () {
        var $footer = $('.footer');
        if (footerTop <= (window.innerHeight + document.body.scrollTop) && !isFooterShow && !isFooterBottom) {
            scrollBottom(8, footerTop, function () {
                $footer.removeAttr('style');
                $('.footer_blank').height(0);
                $footer.find('.close_ico').hide();
            });
            return;
        }

        if (!isFooterShow) {
            footerAnimUp($footer);
            isFooterShow = true;
            return;
        }
        if (isFooterShow && !isFooterBottom) {
            scrollBottom(30, footerTop, function () {
                $footer.removeAttr('style');
                $('.footer_blank').height(0);
                isFooterBottom = true;
                $footer.find('.close_ico').hide();
            });
            isFooterBottom = true;
        }
    });

    //底部close_ico鼠标移入动画
    $('.footer').find('.close_ico').hover(function () {
        $(this).addClass('active');
    }, function () {
        $(this).removeClass('active');
    });

    //底部close_ico鼠标点击
    $('.footer').find('.close_ico').click(function () {
        footerAnimDown($('.footer'));
        isFooterShow = false;
    });

    //底部动画滑出封装
    function footerAnimUp(JQEl) {
        var footerHeight = JQEl.outerHeight() + parseInt(JQEl.css('marginTop'));
        JQEl.find('.close_ico').show();
        JQEl.css({position: 'fixed', zIndex: 23, bottom: -footerHeight + 'px', left: 0, right: 0});
        $('.footer_blank').css({height: footerHeight + 'px'});
        JQEl.animate({bottom: 0}, 300);
    };

    //底部动画滑入封装
    function footerAnimDown(JQEl) {
        var footerHeight = JQEl.outerHeight() + parseInt(JQEl.css('marginTop'));
        JQEl.animate({bottom: -footerHeight + 'px'}, 300, function () {
            $('.footer_blank').height(0);
            JQEl.find('.close_ico').hide();
            setTimeout(function () {
                JQEl.removeAttr('style');
            }, 300);
        });
        isFooterShow = false;
    };

    //直接滚动到底部
    function scrollBottom(speed, Footertop, fn) {
        var top = document.body.scrollTop;
        var timer = null;
        timer = setInterval(function () {
            top += speed;
            if (top >= Footertop) {
                clearInterval(timer);
                fn && fn();
                top = Footertop;
            }
            document.body.scrollTop = top;
        }, 1000 / 60);
    };

    //check isBootom
    function checkIsBottom() {
        if (footerTop < (document.body.scrollTop + window.innerHeight) && (document.body.scrollHeight - document.body.scrollTop) !== window.innerHeight) {
            isFooterBottom = false;
            isFooterShow = true;
        } else if ((document.body.scrollHeight - document.body.scrollTop) === window.innerHeight) {
            $('.footer').removeAttr('style').find('.close_ico').hide();
            $('.footer_blank').height(0);
            isFooterShow = true;
            isFooterBottom = true;
        } else {
            isFooterBottom = false;
            isFooterShow = false;
        }
    };

    //一切弹出遮罩层的都在这里 以及 点击加载更多
    (function () {
        var isLayer = false;
        var modelLayer = $('.more1_hook').add('.more2_hook').add('.more3_hook').add('.more4_hook');
        var prizeLayer = $('.prize1_hook').add('.prize2_hook').add('.prize3_hook').add('.prize4_hook');
        var isNow = 0; //轮播的下标

        try {
            var $grid = $('.works-wrap').packery({
                itemSelector:    '.work-item',
                columnWidth:     '.grid-sizer',
                gutter:          0,
                // gutter: '.gutter-sizer',
                percentPosition: true,
                // isInitLayout:  false,
                // isResizeBound: false
            });
        } catch (e){

        }

        //监听导航
        $('.nav_bar').get(0).addEventListener('click', function (e) {
            var className = e.target.className;
            if (!isLayer && className === 'about_l') {
                alertLayer($('.about_us'));
                isLayer = true;
            }

            if (className === 'server_l') {
                alertLayer($('.server'));
                isLayer = true;
            }
            if ($('.nav_bar').hasClass('js_hook')) {
                $('.nav_bar').slideToggle();
                $('.hidden_menu').removeClass('active');
            }
        }, false);

        //模块点击更多
        $('.model').find('.more').each(function (index, item) {
            $(item).click(function () {
                if (!isLayer) {
                    alertLayer(modelLayer.eq(index));
                    bindAutoPlay(modelLayer.eq(index));
                    isLayer = true;
                } else {
                    closeLayer($('.layer:visible'));
                    isLayer = false;
                }
                return false;
            });
        });

        //点击模块奖项
        $('.model').find('.prize').each(function (index, item) {
            $(item).click(function () {
                if (!isLayer) {
                    alertLayer((prizeLayer.eq(index)));
                    isLayer = true;
                } else {
                    closeLayer($('.layer:visible'));
                    isLayer = false;
                }
                return false
            });
        });

        //model_layer里的按钮吧绑定轮播
        modelLayer.each(function (index, item) {
            bindSlide($(item));
        });

        //works列表的item点击弹出遮罩
        worksItemClick($('.works').find('.work-item'));

        //works 点击加载更多
        $('.load_more').click(function (e) {
            //发送ajax获取的数据
            try {
                var mockData = {
                    code: 0,
                    mes: '成功',
                    result: {
                        works: [
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works91'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: true,
                                title: 'works25'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works2'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works9'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: true,
                                title: 'works5'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works3'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works2'
                            },
                            {
                                img: './../img/work2.jpg',
                                isBig: false,
                                title: 'works1'
                            }
                        ]
                    }
                };

                var compiled = _.template($('#work-template').html());
                $.each(mockData.result.works, function (index, item) {
                    var $item = $(compiled(item));
                    worksItemClick($item);
                    $grid.append($item).packery('appended', $item);
                });
                e.preventDefault();
                return false;
            } catch(err) {

            }
        });

        //绑定点击弹出层的各种点击事件事件 单个
        function bindSlide(JQEl) {
            var oParent = JQEl;
            var sliderLists = oParent.find('.slider_list').find('ul>li');
            var lBtn = oParent.find('.left');
            var rBtn = oParent.find('.right');
            var dots = oParent.find('.dot').find('li');

            dots.each(function (index, dot) {
                $(dot).click(function () {
                    if (index === isNow) return;
                    isNow = index;
                    sliderLists.eq(index).fadeIn().siblings('li').hide();
                    $(this).addClass('active').siblings('li').removeClass('active');
                });
            });

            lBtn.click(function () {
                isNow--;
                if (isNow < 0) isNow = sliderLists.length - 1;
                sliderLists.eq(isNow).fadeIn().siblings('li').hide();
                dots.eq(isNow).addClass('active').siblings('li').removeClass('active');
            });
            rBtn.click(function () {
                isNow++;
                isNow %= sliderLists.length;
                sliderLists.eq(isNow).fadeIn().siblings('li').hide();
                dots.eq(isNow).addClass('active').siblings('li').removeClass('active');
            });


        };

        //绑定自动轮播
        function bindAutoPlay(JQEl) {
            JQEl.get(0).timer = null;
            var sliderLists = JQEl.find('.slider_list').find('ul>li');
            var dots = JQEl.find('.dot').find('li');
            JQEl.get(0).timer = setInterval(function () {
                isNow++;
                isNow %= sliderLists.length;
                sliderLists.eq(isNow).fadeIn().siblings('li').hide();
                dots.eq(isNow).addClass('active').siblings('li').removeClass('active');
                console.log(1);
            }, 2000);
        };

        //关闭遮罩层
        function closeLayer(JQEl, fn) {
            JQEl.get(0).timer && clearInterval(JQEl.get(0).timer);
            JQEl.animate({right: '-100%'}, 600, function () {
                JQEl.hide();
                fn && fn();
            });
        };

        //弹出遮罩层
        function alertLayer(JQEl, fn) {
            //点击 close_ico 关闭遮罩层
            JQEl.find('.close_ico').click(function () {
                closeLayer(JQEl);
                isLayer = false;
            });

            //点击 min_close_ico 关闭遮罩层
            JQEl.find('.min_close_ico').click(function () {
                closeLayer_min(JQEl);
                isLayer = false;
            });

            JQEl.show().animate({right: 0}, 600 , function () {
               fn && fn();
            });
        };

        //最小化关闭遮罩层
        function closeLayer_min(JQEl) {
            JQEl.get(0).timer && clearInterval(JQEl.get(0).timer);
            JQEl.animate({top: '-100%'}, 600, function () {
                JQEl.css({right: '-100%', top: 0}).hide();
            });
        };

        //works专用 给work-item 绑定点击事件
        function worksItemClick(JQEl) {
            //可能要ajax
            JQEl.each(function (index, item) {
                $(item).click(function () {
                    if (isLayer) {
                        closeLayer($('.layer'), function () {
                            $('.works_hook').html(' ');
                        });
                        isLayer = false;
                    } else {
                        var mockData = {
                            title: '标题',
                            subtitle: '副标题',
                            imgList: [
                                './../img/work1.jpg',
                                './../img/work2.jpg',
                                './../img/work2.jpg'
                            ],
                            others: [
                                {
                                    title: '挑战',
                                    content: '無國界醫生需要一個方法，將「救人不分正反」的訊息透過網上活動分享出去。'
                                },
                                {
                                    title: '方案',
                                    content: '為了能夠讓這個沈重的話題能夠變得簡單易明， 我們決定以遊戲的形式包裝這個訊息。遊戲以「救援任務書」為題，邀請玩家以點按的方式，拯救遊戲中需要幫助的人。我們並選擇在最後才向玩家揭曉他們所救的人的身分， 帶出救人跟身分無關，每條人命同等重要。'
                                },
                                {
                                    title: '服务',
                                    content: '網絡活動設計，社交平台，響應式設計'
                                }
                            ]
                        };
                        var compiled = _.template($('#model_template').html());
                        var compiledStr = compiled(mockData);
                        alertLayer($('.works_hook').html(compiledStr), function () {
                            bindSlide($('.works_hook'));
                            bindAutoPlay($('.works_hook'));
                        });
                        isLayer = true;
                    }
                });
            })
        }
    })();

    function getElementTop(el) {
        if (!el) return;
        var top = el.offsetTop;
        var oParent = el.offsetParent;
        while (oParent != null) {
            top += oParent.offsetTop;
            oParent = oParent.offsetParent;
        }

        return top;
    }

    function __delay(time, fn) {
        clearTimeout(GOLBAL_TIMROUT);
        GOLBAL_TIMROUT = setTimeout(fn, time);
    };

});